#!/usr/bin/env python

# copyright 2010 Studio Cypher, LLC
# developer: Will Emigh
# projects@studiocypher.com

# Custom modules
from authentication import user_required
from authentication import get_account_from_user
from models import Account
from models import Planet
from models import Colony
from models import ColonyShip
from models import RecyclingShip
from models import FreighterShip
from models import DestinationRecord
from models import Log
from models import OutPost

# Built-in or Google modules
import cgi
import os
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users


from google.appengine.ext import db

        
class ViewPage(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()

        # If they don't already have an account, redirect to main
        account = get_account_from_user(user)
        if (account == None):
            self.redirect("/")
            return
        
        solar_system = Planet.all()
        error_msg = []
        colony_ships = None
        recycler_ships = None
        freighter_ships = None
        all_ships = ColonyShip.all()
        colony_ships = all_ships.filter('owner =',account).filter('planet =', account.current_planet)
        all_ships = RecyclingShip.all()
        recycler_ships = all_ships.filter('owner =',account).filter('planet =', account.current_planet)
        all_ships = FreighterShip.all()
        freighter_ships = all_ships.filter('owner =',account).filter('planet =', account.current_planet)
        colony_cnt = colony_ships.count()
        recycler_cnt = recycler_ships.count()
        freighter_cnt = freighter_ships.count()
        

        template_values = {'account': account,
                           'current_planet': account.current_planet,
                           'colony_ships': colony_ships,
                           'colony_cnt': colony_cnt,
                           'recycler_ships': recycler_ships,
                           'recycler_cnt': recycler_cnt,
                           'freighter_cnt': freighter_cnt,
                           'freighter_ships': freighter_ships,
                           'solar_system': solar_system,
                           'destination': None,
                           'dest_rec': None,
                           'cost': 0
                           }
        
        path = os.path.join(os.path.dirname(__file__), 'solar_system.html')
        self.response.out.write(template.render(path, template_values))



        
class MoveShip(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()

        # If they don't already have an account, redirect to main
        account = get_account_from_user(user)
        if (account == None):
            self.redirect("/")
            return
        planet = account.current_planet
        
        dest_rec_id = self.request.get("dest_rec_id")
        dest_rec = DestinationRecord.get(dest_rec_id)
        
        colony = None
        colonized = False
        for colony_key in account.current_planet.colonies:
            colony = Colony.get(colony_key)
            if( colony.owner.key() == account.key() ):
                colonized = True
                break
        
        if( colonized ):
            if( colony.resourceStorage.resourceThree >= dest_rec.cost ):
                colony.resourceStorage.resourceThree -= dest_rec.cost
            
                colony.resourceStorage.put()

                account.current_planet = dest_rec.destination
                account.put()

                # adjust location of ship to destination planet    
                ship = db.get( dest_rec.ship )
                ship.planet = dest_rec.destination
                ship.put()
                
        # release dest_rec
        #dest_rec.destination.delete()
        dest_rec.delete()
       
        

        self.redirect('/solar_system/view/')
        
         
class GalacticRescue(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        # If they don't already have an account, redirect to main
        account = get_account_from_user(user)
        if (account == None):
            self.redirect("/")
            return
        
        account.current_planet = account.colonies[0]
        account.put()        

        self.redirect('/solar_system/view/')
        
        
        
        
application = webapp.WSGIApplication(
                                     [('/solar_system/view/', ViewPage),
                                     ('/solar_system/move/', MoveShip),
                                     ('/solar_system/galactic_rescue', GalacticRescue)],
                                     debug=True)									 
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
